//
//  EMOrderSubmitViewController.m
//  ElectronicMall
//
//  Created by 史伟文 on 14/12/24.
//  Copyright (c) 2014年 cczu. All rights reserved.
//

#import "EMOrderSubmitViewController.h"
#import "UINavigationController+EMNavi.h"
#import "ZFTXViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "DataSigner.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "UserInfo.h"
#import "EMUpdateOrderReqBody.h"
#import "EMUpdateOrderRespBody.h"
#import "EMClearCartReqBody.h"
#import "EMClearCartRespBody.h"
@interface EMOrderSubmitViewController ()
{
    AppDelegate *app;
}
@end

@implementation EMOrderSubmitViewController
- (void)viewWillAppear:(BOOL)animated
{
//    [self clearCart];
    [super viewWillAppear:animated];
    self.view.backgroundColor = RGB(242, 242, 242);
    [self.navigationController setNavigationMode:EMNavigationModeDefault andSubMode:0];
    self.title = @"订单已提交";
    
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(0, 0, 30, 32);
    [button setImage:[UIImage imageNamed:@"button_导航_返回_白"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item =[[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.leftBarButtonItem =item;
    
    app = (AppDelegate *)[UIApplication sharedApplication].delegate;
}
- (void)backAction: (UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(20), H(80), W(280), H(40))];
    tipLabel.text = @"订单已提交，请立即支付！";
    tipLabel.textColor = RGB(112, 179, 81);
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.font = [UIFont fontWithName:HEITIMEDIUM size:20];
    [self.view addSubview:tipLabel];
    
    UITableView *comfirmTable = [[UITableView alloc] initWithFrame:CGRectMake(W(20), H(164), W(280), H(132)) style:UITableViewStylePlain];
    comfirmTable.delegate = self;
    comfirmTable.dataSource = self;
    comfirmTable.layer.borderColor = RGB(155, 208, 52).CGColor;
    comfirmTable.layer.borderWidth = 1;
    comfirmTable.layer.cornerRadius = 5;
    comfirmTable.scrollEnabled = NO;
    [self.view addSubview:comfirmTable];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(W(20), H(340), W(280), H(50));
    button.layer.backgroundColor = [UIColor redColor].CGColor;
    button.layer.cornerRadius = 10;
    [button setTitle:@"立即支付" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(gotoPay:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"submitCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    switch (indexPath.row) {
        case 0:
        {
            cell.textLabel.text = [NSString stringWithFormat:@"订单编号：%@", self.orderId];
            cell.textLabel.textColor = [UIColor grayColor];
            cell.textLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
            break;
        }

        case 1:
        {
            cell.textLabel.text = [NSString stringWithFormat:@"订单金额：¥%@", self.payPrice];
            cell.textLabel.textColor = [UIColor grayColor];
            cell.textLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
            break;
        }
        case 2:
        {
            if ([self.payType intValue] == 1) {
                cell.textLabel.text = @"支付方式：货到付款";
            } else {
                cell.textLabel.text = @"支付方式：在线支付";
            }
            cell.textLabel.textColor = [UIColor grayColor];
            cell.textLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
            break;
        }
        default:
            break;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return H(44);
}


- (void)payWithAlipay
{
    NSString *partner = @"2088612525117811";
    NSString *seller = @"13951880999@139.com";
    NSString *privateKey = @"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKsGucfioZxoqJAnaBpC2cYFkQyD62t/ex7XA5D00kPK7eoUMn4ZjxbxfLCpsxVtCe49hGUoIzS0Qg7rYO0B/kwQVhovuA8sq4uAEvrsTXdvGAQPFZ8RHmtRiLDJPcfCogzojJ9YK4dNwn8DyKuMU+8oGMUlCJcZwQIFdzKdRDphAgMBAAECgYAiVQNOYOxYXZoY9hAr1WeqHMv1WzYTKlAo7LjGjJ75BO+lodBRCAh1bpy9ShOtJWps7OR6+ge3OMhZ/l5Ctbe6cP417KjmM3Pr729s2ZRNDjhvvLC9cVFATxl8FNRPJRd+xpkYZB1vyaDnzzot3+cy4WOZsLIThR25ytC9IyXB0QJBAOGNXwv5vUbs7P8Ya57sDSzhfeTvSiSLYbZHq79CCUBo3y6JdlK5tT60tjH8Dm+02ecj+TK/tJPm7N6f/IlgpwsCQQDCHQwwJGJQVmjjTAw1TpsDIy7PxhX+RLQi9rP3rzuQBtJimx0+njBB8dBKBBa6S28Qaqg23LCRgL/Bhx6myRfDAkEAkiJDK4IiFPraTiinSa8MlkB+jb5Pnj/EDhJ/fwos7lNEDmW3iL+TY044IUh6nfthlrUi9rNoLs9WNqMXPnalowJAQT6aNiREl1Qz9RI+mDxPhgJxXYzrH4fgNFBPtVTE5GgmltYkQkPRXJj2taoiKYPpVM9EswwCnSV1TosoFk9JGQJBANcrmxWgtqnp29idXdxrLlXnWQ9j6fr/z3rKRK5rLLDOuY6lr1HJZWzoOsGLchQsMz+T55foD++MhuCdiRP4OZk=";
    
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = self.orderId; //订单ID（由商家自行制定）
    order.productName = @"沃佳先生商品"; //商品标题
    order.productDescription = @"快捷支付"; //商品描述
    order.amount = self.payPrice; //商品价格
    order.notifyURL =  @"http://www.wojiaxiansheng.com"; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"yunbeiMall";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut1 = %@",resultDic);
            [self payFinishedWithErrorCode:[resultDic[@"resultStatus"] intValue]];
        }];
        
    }
}
+ (void)callBackActionWithURL:(NSURL *)url
{
    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
        // 这里是调用支付宝客户端的回调，url就是在appdelelgate里面传过来的
        NSLog(@"reslut2 = %@",resultDic);
        [[[self alloc] init] payFinishedWithErrorCode:[resultDic[@"resultStatus"] intValue]];
    }];
}
- (void)payFinishedWithErrorCode:(int)code
{
    switch (code) {
        case 9000:
        {
            [app showTip:@"支付成功"];
            [self updateOrderInfo];
//            [self clearCart];
            [self payFinishedActionWithTitle:@"订单已支付" andContent:@"支付成功，正在发货"];
            break;
        }
        case 8000:
        {
            [app showTip:@"正在处理"];
            break;
        }
        case 4000:
        {
            [app showTip:@"支付失败"];
            break;
        }
        case 6001:
        {
            [app showTip:@"取消支付"];
            break;
        }
        case 6002:
        {
            [app showTip:@"网络故障"];
            break;
        }
        default:
        {
            [app showTip:@"未知错误"];
            break;
        }
    }
}
- (void)updateOrderInfo
{
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMUpdateOrderReqBody *reqBody = [[EMUpdateOrderReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"UPDATE-ORDER";
    reqBody.USERID = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    reqBody.ORDERNO = self.orderId;
    reqBody.REALPRICE = self.payPrice;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMUpdateOrderRespBody *respBody = [EMUpdateOrderRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
}
- (void)clearCart
{
//    NSMutableString *goodIds = [[NSMutableString alloc] init];
//    for (int i = 0; i < self.goodArray.count; i ++) {
//        [goodIds appendFormat:@"\"%@\"", self.goodArray[i][0]];
//        if (i != self.goodArray.count-1) {
//            [goodIds appendString:@","];
//        }
//    }
//    goodIds = [[NSString stringWithFormat:@"{%@}", goodIds] mutableCopy];
    
    NSMutableArray *goodIds = [[NSMutableArray alloc] init];
    for (int i = 0; i < self.goodArray.count; i ++) {
        [goodIds addObject:@{@"id":self.goodArray[i][0]}];
    }
    
    
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    EMClearCartReqBody *reqBody = [[EMClearCartReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"IOS-DELETE-SHOPPING-CARTS";
    reqBody.NAME = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    reqBody.IDS = goodIds;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMClearCartRespBody *respBody = [EMClearCartRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
    
}


- (void)gotoPay: (UIButton *)sender
{
    if ([self.payType intValue] == 1) {
        [self updateOrderInfo];
        [self clearCart];
        [self payFinishedActionWithTitle:@"订单已提交" andContent:@"正在发货"];
        // 货到付款
    } else {
        // 支付宝
        [self payWithAlipay];
    }
}
- (void)payFinishedActionWithTitle:(NSString *)title andContent:(NSString *)content
{
    ZFTXViewController *controller = [[ZFTXViewController alloc] init];
    controller.contentText = content;
    controller.titleText = title;
    [self.navigationController pushViewController:controller animated:YES];
}
@end
